/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.adama.controller;

import fr.adama.dto.AdherentDTO;
import fr.adama.entite.Adherent;
import fr.adama.service.AdherentService;
import java.util.List;
import java.util.Locale;
import javax.validation.Valid;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author mini-john
 */
@Controller
public class AdherentController {

    private static final Logger logger = LoggerFactory.getLogger(AdherentController.class);

    @Autowired
    private AdherentService adherentService;

    @Autowired
    private MessageSource messageSource;

    @RequestMapping("/adherent/index.do")
    public ModelAndView index() {
        logger.info(System.getProperty("org.dozer.util.DozerProxyResolver"));
        return new ModelAndView("adherent/index");
    }

    @RequestMapping(method = RequestMethod.GET, value = "/adherent/add.do")
    public String addAdherent(ModelMap model) {

        AdherentDTO adherent = new AdherentDTO();
        model.addAttribute("adherent", adherent);
        return "adherent/add";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/adherent/add.do")
    public ModelAndView insertAdherent(@Valid @ModelAttribute("adherent") AdherentDTO adherentDto, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) {
        if (result.hasErrors()) {

            return new ModelAndView("adherent/add", "adherent", adherentDto);
        }

        try {
            logger.info("Ajout de l'adherent {}", adherentDto.getNomPrenom());
        Long    adherentDtoId = adherentService.add(adherentDto, Adherent.class);
        adherentDto.setId(adherentDtoId);
            redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("Adherent.add.success", new String[]{""}, new Locale("fr")));
        } catch (DataIntegrityViolationException ex) {
            logger.error("Erreur d'ajout d'adherent{}",adherentDto.getNomPrenom(), ex);
            if (ex.getCause() instanceof ConstraintViolationException) {

                ConstraintViolationException cdts = (ConstraintViolationException) ex.getCause();
                if (cdts.getConstraintName().equalsIgnoreCase("NOMPRENOMEXISTADHERENT")) {
                    ObjectError error = new ObjectError("nomPrenom", messageSource.getMessage("Adherent.add.error.adherent.exist", new String[]{adherentDto.getNomPrenom()}, new Locale("fr")));
                    result.addError(error);
                    return new ModelAndView("adherent/add", "adherent", adherentDto);
                }

            }
        }
        return new ModelAndView("redirect:/adherent/show.do", "id", adherentDto.getId());
    }

    @RequestMapping(method = RequestMethod.GET, value = "/adherent/list.do")
    public ModelAndView listAdherent() {
        List<AdherentDTO> listAdherent = adherentService.findAll(Adherent.class, AdherentDTO.class);
        return new ModelAndView("adherent/list", "listAdherent", listAdherent);

    }

    @RequestMapping(method = RequestMethod.GET, value = "/adherent/show.do")
    public ModelAndView getAdherentById(@RequestParam(required = true, value = "id") Long id, RedirectAttributes redirectAttributes) {
        logger.info("Vision de l'adhrent {}", id);
        AdherentDTO adherent = adherentService.getById(id, Adherent.class, AdherentDTO.class);

        return new ModelAndView("adherent/show", "adherent", adherent);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/adherent/update.do")
    public ModelAndView updateAdherentForm(@RequestParam(required = true, value = "id") Long id) {
        AdherentDTO adherent = adherentService.getById(id, Adherent.class, AdherentDTO.class);

        return new ModelAndView("adherent/update", "adherent", adherent);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/adherent/update.do")
    public ModelAndView updateAdherent(@Valid @ModelAttribute("adherent") AdherentDTO adherentDto, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) {
        if (result.hasErrors()) {

            return new ModelAndView("adherent/update", "adherent", adherentDto);
        }

        try {
            logger.info("Mis à jour de l'adherent {}", adherentDto.getNomPrenom());
            adherentService.update(adherentDto, Adherent.class);
            redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("Adherent.update.success", new String[]{""}, new Locale("fr")));
        } catch (DataIntegrityViolationException ex) {
            logger.error("Erreur demis a jour d'adherent {}",adherentDto.getNomPrenom(), ex);
            if (ex.getCause() instanceof ConstraintViolationException) {
                ConstraintViolationException cdts = (ConstraintViolationException) ex.getCause();
                if (cdts.getConstraintName().equalsIgnoreCase("NOMPRENOMEXISTADHERENT")) {
                    ObjectError error = new ObjectError("nomPrenom", messageSource.getMessage("Adherent.update.error.adherent.exist", new String[]{adherentDto.getNomPrenom()}, new Locale("fr")));
                    result.addError(error);
                    return new ModelAndView("adherent/update", "adherent", adherentDto);
                }

            }

        }
        return new ModelAndView("redirect:/adherent/show.do", "id", adherentDto.getId());
    }

    @RequestMapping(method = RequestMethod.GET, value = "/adherent/search.do")
    public String searchPage(ModelMap model
    ) {
        AdherentDTO adherent = new AdherentDTO();
        model.addAttribute("adherent", adherent);
        return "adherent/search";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/adherent/search.do")
    public ModelAndView search(@ModelAttribute("adherent") AdherentDTO adherentDto
    ) {
        List<AdherentDTO> listAdherent = adherentService.searchByEntity(adherentDto);
        return new ModelAndView("adherent/search", "listAdherent", listAdherent);
    }

}
